package yl.hs.bmipfull.utils.Gps;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import yl.hs.bmipfull.daos.production.ITransTaskDao;
import yl.hs.bmipfull.daos.vehiclemanage.ITruckInfoDao;
import yl.hs.bmipfull.pojo.production.TransTaskEntity;
import yl.hs.bmipfull.pojo.vehiclemanage.TruckInfoEntity;
import yl.hs.bmipfull.utils.CK;
import yl.hs.bmipfull.utils.WebUtil;

import javax.annotation.PostConstruct;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 作用:   <br/>
 * 创建时间: 2022-07-26 11:14 <br/>
 *
 * @author 吴高丰
 */
@Component
public class GpsLogin implements Runnable {
    @Value("${gpsswitch}")
    private boolean gpsswitch;
    @Value("${gpsurl}")
    private String gpsurl;
    @Value("${gpskey}")
    private String gpskey;
    @Value("${gpssecret}")
    private String gpssecret;
    @Value("${customername}")
    private String customername;
    private List<TruckInfoEntity> trucklist;//车辆信息
    private List<TransTaskEntity> transTaskEntityList;//派车信息
    @Autowired
    ITruckInfoDao truckInfoDao;
    @Autowired
    ITransTaskDao transTaskDao;

    @PostConstruct
    public void loadGpsData() {
        if (gpsswitch) {
            loginGps();
            init();
        } else {
            return;
        }
    }

    //登录验证GPS信息
    public void loginGps() {
        if (gpsswitch) {
            try {
                var token = WebUtil.requestPost(gpsurl + "/video/user/api/login?key=" + gpskey + "&secret=" + gpssecret, null);
                JSONObject jo = JSONObject.parseObject(token);
                var data = (Map<String, Object>) jo.get("data");
                var result = data.get("token").toString();
                CK.GpsToken = result;
                if (!CK.GpsToken.isEmpty()) {
                    List<String> customerID = new ArrayList<>();
                    var getcustomer = WebUtil.requestGpsPost(gpsurl + "/video/client/tree", null);
                    JSONObject customer = JSONObject.parseObject(getcustomer);
                    var customerList = (List<Object>) customer.get("data");
                    for (Object o : customerList) {
                        JSONObject cus = JSONObject.parseObject(o.toString());
                        var item = cus.get("clientName").toString();
                        if (customername.contains(item)) {
                            customerID.add(cus.get("clientId").toString());
                        }
                    }
                    CK.CarList = GetCarId(customerID);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //根据客户编号查询客户下的车辆信息
    public List<String> GetCarId(List<String> customerID) {
        try {
            Map<String, Object> dic = new HashMap<>();
            dic.put("cids", String.join(",", customerID));
            var caridlist = WebUtil.requestGpsPost(gpsurl + "/video/vehicle/simple/list", dic);
            JSONObject jo = JSONObject.parseObject(caridlist);
            var carlist = (List<Object>) jo.get("data");
            List<String> car = new ArrayList<>();
            for (Object o : carlist) {
                var item = JSONObject.parseObject(o.toString());
                car.add(item.get("vehicleId").toString());
            }
            return car;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public void init() {
        //启动线程实例
        new Thread(this).start();
    }

    @Override
    public void run() {
        synchronized (this) {
            while (true) {
                try {
                    carBreak();
                } catch (Exception e) {

                    loginGps();
                }
            }
        }
    }

    //车辆自动排队逻辑
    public void carBreak() throws Exception {
        try {
            var carinfo = "";
            if (CK.CarList != null && CK.CarList.size() > 0) {
                //回厂车辆集合
                List<String> breakCar = new ArrayList<>();
                //外出车辆集合
                List<String> outCar = new ArrayList<>();
                //全部商砼车辆信息
                trucklist = truckInfoDao.queryAll("mixTruck");
                //未完成的派车信息
                //transTaskEntityList = transTaskDao.queryByState();
                //车辆信息定位合集
                List<Object> allcar = new ArrayList<>();
                carinfo = String.join(",", CK.CarList);
                var url = gpsurl + "/video/monitor/getVehicleDataByIds?ids=" + carinfo;
                var result = WebUtil.requestGpsPost(url, null);
                JSONObject jo = JSONObject.parseObject(result);
                if (!jo.get("code").toString().equals("0000")) {
                    loginGps();
                    Thread.sleep(10000);
                    return;
                }
                var resultList = (List<Object>) jo.get("data");
                for (Object items : resultList) {
                    JSONObject item = JSONObject.parseObject(items.toString());
                    var xiugai = gcj02_To_Bd09(
                            item.get("lat") == null ? 0 : Double.valueOf(item.get("lat").toString()),
                            item.get("lng") == null ? 0 : Double.valueOf(item.get("lng").toString())
                    );
                    item.remove("lat");
                    item.remove("lng");
                    item.put("lat", String.valueOf(xiugai[0]));
                    item.put("lng", String.valueOf(xiugai[1]));
                    var car = trucklist.stream().filter(t -> t.getTruckPlate().equals(item.get("vehicle_name").toString())).toList();
                    if (car == null || car.size() == 0) {
                        continue;
                    }
                    var carname = car.get(0);
                    item.put("truckCode", carname.getTruckCode());
                    if (!item.get("stateStr").toString().isEmpty() && !item.get("stateStr").toString().contains("离线") && carname.getState() != 90 && !item.get("stateStr").toString().contains("补传")) {
                        var customer = customername.split(",")[0];
                        if (item.get("stateStr").toString().contains(customer)) {
                            if (carname.getState() == 30 || carname.getState() == 50 || carname.getState() == 60) {
                                breakCar.add(carname.getSn());
                            }
                        } else {
                            if (carname.getState() == 10 || carname.getState() == 20) {
                                outCar.add(carname.getSn());
                            }
                        }
                    }
                    allcar.add(item);
                    //更改车辆状态
                    if (breakCar != null && breakCar.size() > 0) {
                        truckInfoDao.changeStateBySn(breakCar.toArray(), (short) 10);
                    }
                    if (outCar != null && outCar.size() > 0) {
                        truckInfoDao.changeStateBySn(outCar.toArray(), (short) 30);
                    }
                    //更改派车状态
                    if (outCar != null && outCar.size() > 0) {
                        transTaskDao.changeStateBySN(outCar.toArray(), (short) 2);
                    }
                }
                CK.locationCar = allcar;
            }
        } catch (Exception ee) {

        } finally {
            Thread.sleep(10000);
        }
    }

    //坐标转换偏移转换函数
    public static double pi = 3.1415926535897932384626;
    public static double x_pi = 3.14159265358979324 * 3000.0 / 180.0;
    public static double a = 6378245.0;
    public static double ee = 0.00669342162296594323;

    public static double[] gcj02_To_Bd09(double lat, double lon) {
        double x = lon, y = lat;
        double z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
        double theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
        double tempLon = z * Math.cos(theta) + 0.0065;
        double tempLat = z * Math.sin(theta) + 0.006;
        double[] gps = {tempLat, tempLon};
        return gps;
    }
    @PostConstruct
    @Scheduled(cron="50 10 0 * * ?")
    public void GetTQ(){
        try{
            URL url = new URL("http://t.weather.itboy.net/api/weather/city/101181801");
            InputStreamReader isReader =  new InputStreamReader(url.openStream(),"UTF-8");//“UTF- 8”万国码，可以显示中文，这是为了防止乱码
            BufferedReader br = new BufferedReader(isReader);//采用缓冲式读入
            String str;
            if((str = br.readLine()) != null){
                String regex="\\p{Punct}+";
                String digit[]=str.split(regex);
                CK.Weather =digit[49]+"年"+digit[50]+"月"+digit[51]+"日"+digit[53]+","+digit[22]+digit[18]+","+digit[47]+"~"+digit[45]+","+digit[67]+" "+digit[63]+digit[65];
            }
            br.close();//网上资源使用结束后，数据流及时关闭
            isReader.close();
        }
        catch(Exception exp){
            CK.Weather="暂无数据";
        }
    }
}
